package net.oschina.simpleplus.ctrl;

import java.util.Date;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import net.oschina.simpleplus.dao.NoteDao;
import net.oschina.simpleplus.dao.UserDao;
import net.oschina.simpleplus.entity.Note;
import net.oschina.simpleplus.entity.User;
import net.oschina.simpleplus.jwt.JwtFactory;
import net.oschina.simpleplus.jwt.SkipJwtAuth;
import net.oschina.simpleplus.kits.MapKit;
import net.oschina.simpleplus.vo.UserVo;

@RestController
public class UserCtrl {
	
	@Autowired private UserDao userDao;
	
	@Autowired private JwtFactory jwtFactory;
	
	@Autowired private NoteDao noteDao;

	@SkipJwtAuth
	@PostMapping("/login")
	public Map<String, Object> login(@RequestParam("email")String email, @RequestParam("passwd") String passwd){
		Subject subject = SecurityUtils.getSubject();
		subject.login(new UsernamePasswordToken(email, passwd));
		
		Map<String, Object> resp = MapKit.buildSuccMap();
		UserVo userVo = new UserVo(userDao.selectByEmail(email));
		resp.put("token", jwtFactory.generateToken(userVo));
		resp.put("user", userVo);
		return resp;
	}
	
	/**
	 * http://localhost:8899/register
	 * @param email
	 * @param passwd
	 * @return
	 */
	@SkipJwtAuth
	@PostMapping("/register")
	public Map<String, Object> register(@RequestParam("email")String email, @RequestParam("passwd") String passwd){
		User user = User.createNewUser(email, passwd);
		userDao.saveNewUser(user);
		return MapKit.buildSuccMap();
	}
	
	@GetMapping("/getUserInfo")
	public Map<String, Object> getUserInfo(UserVo userVo){
		Map<String, Object> resp = MapKit.buildSuccMap();
		resp.put("user", userVo);
		resp.put("noteList", noteDao.selectNotes(userVo.getId()));
		return resp;
	}
	
	
	@PostMapping("/saveNote")
	public Map<String, Object> saveNote(UserVo userVo, @RequestBody Note note){
		if(!userVo.getId().equals(note.getUserId())){
			note.setUserId(userVo.getId());
		}
		note.setLastUpdateTime(new Date());
		noteDao.saveNewNote(note);
		Map<String, Object> resp = MapKit.buildSuccMap();
		resp.put("note", note);
		return resp;
	}
	
	
	@PostMapping("/updateNote")
	public Map<String, Object> updateNote(UserVo userVo, @RequestBody Note note){
		if(!userVo.getId().equals(note.getUserId())){
			note.setUserId(userVo.getId());
		}
		note.setLastUpdateTime(new Date());
		noteDao.updateNote(note);
		Map<String, Object> resp = MapKit.buildSuccMap();
		resp.put("note", note);
		return resp;
	}
}
